package com.example.administrator.shzs.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.shzs.R;
import com.example.administrator.shzs.activity.BaseActivity;
import com.example.administrator.shzs.adapter.SearchGridviewAdapter;
import com.example.administrator.shzs.adapter.HomeShopListAdapter;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.entity.MerchantData;
import com.example.administrator.shzs.parse.ParseIndexXrecycleView;
import com.example.administrator.shzs.url.Contents;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 搜索界面
 */
public class SearchActivity extends BaseActivity {

    @Bind(R.id.soso_back)
    ImageView sosoBack;
    @Bind(R.id.soso)
    TextView soso;
    @Bind(R.id.edit)
    ImageView edit;
    @Bind(R.id.soso_grid)
    GridView sosoGrid;
    @Bind(R.id.activity_index_so_so)
    LinearLayout activityIndexSoSo;
    @Bind(R.id.edittext)
    EditText edittext;
    @Bind(R.id.hot_soso)
    LinearLayout hotSoso;
    @Bind(R.id.index_hot_xrecycleview)
    XRecyclerView indexHotXrecycleview;
    @Bind(R.id.working)
    ImageView working;


    private String shopname;

    private SearchGridviewAdapter adapter;
    private List<Map<Object, Object>> datalist = new ArrayList<>();

    //默认加载列表
    private HomeShopListAdapter Xadapter;
    private List<MerchantData.ListBean> datalistX; //默认加载
    private List<MerchantData.ListBean> datalistXo;//更多加载

    //页数
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index_so_so);
        ButterKnife.bind(this);
        MyApplication.app.activityList.add(this);
        indexHotXrecycleview.setLayoutManager(new LinearLayoutManager(this));

        initdata();
//        //获取网络数据
        //点击事件
        inevent();

        indexHotXrecycleview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                initDataFromeWeb();
            }

            @Override
            public void onLoadMore() {
                page++;
                initDataFromeWeb();
            }
        });
    }

    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                        working.setVisibility(View.VISIBLE);


                    indexHotXrecycleview.refreshComplete();
                    indexHotXrecycleview.loadMoreComplete();
                    break;
                case 1:

                    Xadapter = new HomeShopListAdapter(SearchActivity.this, datalistX);
                    indexHotXrecycleview.setAdapter(Xadapter);
                    indexHotXrecycleview.setVisibility(View.VISIBLE);
                    Xadapter.setOnItemClickListener(new HomeShopListAdapter.OnRecyclerViewItemClickListener() {
                        @Override
                        public void onItemClick(MerchantData.ListBean merchantData) {

                            Intent intent = new Intent(SearchActivity.this, ShopActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("MerchantData", merchantData);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }

                        @Override
                        public void onShopPayClick(MerchantData.ListBean merchantData) {

                            Intent offlinePay = new Intent(SearchActivity.this, OfflinePayActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("merchantdata", merchantData);
                            offlinePay.putExtras(bundle);

                            startActivity(offlinePay);
                        }
                    });

                    break;
                case 2:
                    datalistX.addAll(datalistXo);
                    Xadapter.notifyDataSetChanged();
                    datalistXo.clear();
                    indexHotXrecycleview.loadMoreComplete();
                    break;
            }
        }
    };

    //获取网络数据
    private void initDataFromeWeb() {
        String url = Contents.INDEX_SOSO + "?lat=" + MyApplication.app.getLatitude() + "&lng=" + MyApplication.app.getLongitude()
                + "&shopname=" + shopname + "&pagesize=20" + "&pageindex=" + page;

        Request qequest = new Request.Builder().url(url).build();
        Contents.okhttp.newCall(qequest).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                hander.sendEmptyMessage(0);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String request = response.body().string();

                if (page == 1) {
                    try {
                        datalistX = ParseIndexXrecycleView.getIndexXrecyclView(request);
                        if (datalistX.size() > 0) {
                            hander.sendEmptyMessage(1);

                        } else {
                            hander.sendEmptyMessage(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                } else {
                    try {
                        datalistXo = ParseIndexXrecycleView.getIndexXrecyclView(request);
                        if (datalistXo.size() > 0) {
                            hander.sendEmptyMessage(2);
                        } else {
                            hander.sendEmptyMessage(0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }


    private void initdata() {

        final String[] name = new String[]{
                "黄焖鸡", "麻辣烫", "热干面", "米线", "披萨", "串串香", "砂锅面", "奶茶"
        };
        for (int i = 0; i < name.length; i++) {
            Map<Object, Object> map = new HashMap<>();
            map.put("name", name[i]);
            datalist.add(map);
        }
        adapter = new SearchGridviewAdapter(this, datalist);
        sosoGrid.setAdapter(adapter);
        sosoGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView text = (TextView) view.findViewById(R.id.index_hot_soso_item);
                edittext.setText(text.getText());
                shopname = edittext.getText().toString();
                initDataFromeWeb();
            }
        });

    }

    private void inevent() {
        sosoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();

            }
        });

        soso.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shopname = edittext.getText().toString();
                initDataFromeWeb();


            }
        });

        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.toString().trim().length() != 0) {
                    hotSoso.setVisibility(View.GONE);
                    shopname = edittext.getText().toString();
//                    initDataFromeWeb();
                } else {
                    hotSoso.setVisibility(View.VISIBLE);
                    working.setVisibility(View.GONE);
                    indexHotXrecycleview.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });


    }


}
